/**
 * 分钟级交易模块
 * 负责处理分钟级交易页面的交互和数据更新
 */

// 在Alpine.js初始化时注册数据
document.addEventListener('alpine:init', () => {
  Alpine.data('minuteTrading', () => ({
    // 股票基本信息
    stockCode: '600036',
    stockName: '招商银行',
    currentPrice: 42.85,
    priceChange: 2.35,
    currentTime: '',
    
    // 图表相关
    timeScales: ['1分钟', '5分钟', '15分钟', '30分钟', '60分钟'],
    currentTimeScale: '1分钟',
    klineChart: null,
    
    // 交易信号
    tradingSignal: {
      signal: '买入信号',
      strength: '高',
      duration: '15分钟'
    },
    
    // 短期预测
    shortTermPrediction: {
      thirtyMin: 75,
      sixtyMin: 68,
      trendStrength: '中高'
    },
    
    // 风险控制
    riskControl: {
      stopLoss: 41.80,
      takeProfit: 44.20,
      riskRatio: '1:2.4'
    },
    
    // 交易建议
    tradingAdvice: {
      action: '短线买入',
      position: '15%-25%',
      holdingTime: '约2小时'
    },
    
    // 初始化
    init() {
      this.currentTime = this.getCurrentTime();
      this.initKlineChart();
      this.startRealTimeUpdate();
      this.initWebSocket();
      
      // 检查URL参数中是否有股票代码
      const urlParams = new URLSearchParams(window.location.search);
      const stockCode = urlParams.get('stock');
      if (stockCode) {
        this.loadStockData(stockCode);
      }
    },
    
    // 获取当前时间
    getCurrentTime() {
      return new Date().toLocaleTimeString('zh-CN', {
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    
    // 设置时间尺度
    setTimeScale(scale) {
      this.currentTimeScale = scale;
      // 更新K线图表的时间尺度
      this.updateKlineData();
    },
    
    // 初始化K线图表
    initKlineChart() {
      const chartDom = document.getElementById('kline-chart');
      if (!chartDom) return;
      
      const myChart = echarts.init(chartDom);
      
      const upColor = '#00da3c';
      const downColor = '#ec0000';
      
      function generateData(count) {
        const data = [];
        let now = new Date();
        let basePrice = 42.85;
        
        for (let i = 0; i < count; i++) {
          const open = basePrice + Math.random() * 2 - 1;
          const close = open + Math.random() * 2 - 1;
          const low = Math.min(open, close) - Math.random() * 0.5;
          const high = Math.max(open, close) + Math.random() * 0.5;
          
          data.push({
            time: new Date(now - (count - i) * 60000),
            open,
            close,
            low,
            high,
            volume: Math.round(Math.random() * 10000)
          });
          
          basePrice = close;
        }
        
        return data;
      }
      
      const data = generateData(100);
      
      const option = {
        animation: false,
        legend: {
          bottom: 10,
          left: 'center',
          data: ['K线', 'MA5', 'MA10', 'MA20', 'MA30']
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          borderWidth: 1,
          borderColor: '#ccc',
          padding: 10,
          textStyle: {
            color: '#000'
          }
        },
        axisPointer: {
          link: [{ xAxisIndex: [0, 1] }],
          label: {
            backgroundColor: '#777'
          }
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: false
            },
            brush: {
              type: ['lineX', 'clear']
            }
          }
        },
        grid: [
          {
            left: '10%',
            right: '8%',
            height: '50%'
          },
          {
            left: '10%',
            right: '8%',
            top: '63%',
            height: '16%'
          }
        ],
        xAxis: [
          {
            type: 'time',
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            min: 'dataMin',
            max: 'dataMax'
          },
          {
            type: 'time',
            gridIndex: 1,
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            min: 'dataMin',
            max: 'dataMax'
          }
        ],
        yAxis: [
          {
            scale: true,
            splitArea: {
              show: true
            }
          },
          {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLabel: { show: false },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: [0, 1],
            start: 80,
            end: 100
          },
          {
            show: true,
            xAxisIndex: [0, 1],
            type: 'slider',
            top: '85%',
            start: 80,
            end: 100
          }
        ],
        series: [
          {
            name: 'K线',
            type: 'candlestick',
            data: data.map(item => [
              item.time,
              item.open,
              item.close,
              item.low,
              item.high
            ]),
            itemStyle: {
              color: upColor,
              color0: downColor,
              borderColor: undefined,
              borderColor0: undefined
            }
          },
          {
            name: '成交量',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data.map(item => [
              item.time,
              item.volume,
              item.close > item.open ? 1 : -1
            ]),
            itemStyle: {
              color: function(params) {
                return params.data[2] > 0 ? upColor : downColor;
              }
            }
          }
        ]
      };
      
      myChart.setOption(option);
      
      // 窗口大小变化时自动调整图表大小
      window.addEventListener('resize', () => myChart.resize());
      
      this.klineChart = myChart;
    },
    
    // 开始实时更新
    startRealTimeUpdate() {
      setInterval(() => {
        this.currentTime = this.getCurrentTime();
        
        // 模拟价格变化
        const priceChange = (Math.random() - 0.5) * 0.2;
        this.currentPrice = +(this.currentPrice + priceChange).toFixed(2);
        this.priceChange = +((this.currentPrice - 42.85) / 42.85 * 100).toFixed(2);
        
        // 更新K线图表
        this.updateKlineData();
      }, 5000); // 每5秒更新一次
    },
    
    // 更新K线数据
    updateKlineData() {
      if (!this.klineChart) return;
      
      const option = this.klineChart.getOption();
      if (!option.series || !option.series[0] || !option.series[0].data) return;
      
      const data = option.series[0].data;
      const volumeData = option.series[1].data;
      
      const now = new Date();
      const lastClose = data[data.length - 1][2];
      const open = lastClose + (Math.random() - 0.5) * 0.2;
      const close = this.currentPrice;
      const low = Math.min(open, close) - Math.random() * 0.1;
      const high = Math.max(open, close) + Math.random() * 0.1;
      const volume = Math.round(Math.random() * 10000);
      
      // 移除最旧的数据点
      data.shift();
      volumeData.shift();
      
      // 添加新的数据点
      data.push([now, open, close, low, high]);
      volumeData.push([now, volume, close > open ? 1 : -1]);
      
      // 更新图表
      this.klineChart.setOption({
        series: [
          { data: data },
          { data: volumeData }
        ]
      });
    },
    
    // 初始化WebSocket连接
    initWebSocket() {
      if (!window.wsManager) return;
      
      // 订阅股票实时数据
      window.wsManager.subscribe('stock_price', (data) => {
        if (data && data.code === this.stockCode) {
          this.updateStockData(data);
        }
      });
    },
    
    // 更新股票数据
    updateStockData(data) {
      this.currentPrice = data.price;
      this.priceChange = data.change;
      
      // 更新交易信号和预测
      if (data.tradingSignal) {
        this.tradingSignal = data.tradingSignal;
      }
      
      if (data.prediction) {
        this.shortTermPrediction = data.prediction;
      }
      
      if (data.riskControl) {
        this.riskControl = data.riskControl;
      }
      
      if (data.advice) {
        this.tradingAdvice = data.advice;
      }
    },
    
    // 加载特定股票数据
    loadStockData(stockCode) {
      this.stockCode = stockCode;
      
      // 获取股票名称
      fetch(`/api/stock/info?code=${stockCode}`)
        .then(response => response.json())
        .then(data => {
          if (data && data.name) {
            this.stockName = data.name;
          }
        })
        .catch(error => {
          console.error('获取股票信息失败:', error);
        });
      
      // 获取历史K线数据
      fetch(`/api/stock/kline?code=${stockCode}&period=${this.currentTimeScale}`)
        .then(response => response.json())
        .then(data => {
          if (data && data.kline) {
            this.updateKlineWithHistoricalData(data.kline);
          }
        })
        .catch(error => {
          console.error('获取K线数据失败:', error);
        });
    },
    
    // 使用历史数据更新K线图
    updateKlineWithHistoricalData(klineData) {
      if (!this.klineChart || !klineData || klineData.length === 0) return;
      
      const formattedData = klineData.map(item => [
        new Date(item.time),
        item.open,
        item.close,
        item.low,
        item.high
      ]);
      
      const volumeData = klineData.map(item => [
        new Date(item.time),
        item.volume,
        item.close > item.open ? 1 : -1
      ]);
      
      this.klineChart.setOption({
        series: [
          { data: formattedData },
          { data: volumeData }
        ]
      });
    }
  }));
});